package platform

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"

	hyperNexusCommon "github.com/wzh200x/hyperNexus/hyperNexusCommon"
	"github.com/wzh200x/hyperNexus/hyperNexusErr"
	"github.com/wzh200x/hyperNexus/hyperNexusProtocol/interfaceServerProtocol"
	"github.com/wzh200x/hyperNexus/hyperNexusType"
)

// 微信登录返回的会话信息
type VivoSession struct {
	Code  int          `json:"code"`
	Msg   string       `json:"msg"`
	Datat VivoUserData `json:"data"`
}

type VivoUserData struct {
	HasEncrypt   bool   `json:"hasEncrypt"`
	OpenId       string `json:"openId"`
	NickName     string `json:"nickName"`
	SmallAvatar  string `json:"smallAvatar"`
	BiggerAvatar string `json:"biggerAvatar"`
	Gender       int    `json:"gender"`
}

type PlatformVivo struct {
	PlatformBase
}

func (p *PlatformVivo) Login(ctx context.Context, input *interfaceServerProtocol.LoginRequest) (output interfaceServerProtocol.LoginResponse, err error) {
	// 1. 通过code获取微信会话信息
	session, err := p.GetSession(input.PrivateKey, input.AppSecret, input.PackageName, input.Code)
	if err != nil {
		output.Code = hyperNexusErr.ErrCode_PlatformLoginFailed
		output.Msg = err.Error()
		return output, err
	}
	output.Code = 0
	output.OpenId = session.Datat.OpenId
	return output, nil
}

// 通过code获取微信会话信息
func (p *PlatformVivo) GetSession(privateKey string, appSecret string, packageName string, code string) (*VivoSession, error) {
	nowTime := hyperNexusCommon.GetCurrentTimeMilliseconds()
	nonceStr := hyperNexusCommon.GenerateRandomString32()
	signStr := fmt.Sprintf("appKey=%s&appSecret=%s&nonce=%s&pkgName=%s&timestamp=%d&token=%s",
		privateKey, appSecret, nonceStr, packageName, nowTime, code)
	signature := hyperNexusCommon.Sha256Hex(signStr)
	url := fmt.Sprintf("https://quickgame.vivo.com.cn/api/quickgame/cp/account/userInfo?pkgName=%s&token=%s&timestamp=%d&nonce=%s&signature=%s&encodeFlag=false",
		packageName, code, nowTime, nonceStr, signature)

	resp, err := http.Get(url)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	var session VivoSession
	if err := json.Unmarshal(body, &session); err != nil {
		return nil, err
	}

	if session.Code != 0 {
		return nil, fmt.Errorf("VivoAPI错误: %d %s", session.Code, session.Msg)
	}

	return &session, nil
}

func NewPlatformVivo() *PlatformVivo {
	return &PlatformVivo{
		PlatformBase: PlatformBase{
			PlatformID: hyperNexusType.PlatformTypeVivo,
		},
	}
}
